package http;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet 工具类 可以在普通类中获取 HttpServletRequest、HttpSession、HttpServletResponse
 * @author huangqiankun
 * @date 2020年5月13日下午5:30:19
 */
public class ServletUtils {

	/**
	 * 获取 HttpServletRequest
	 */
	public static HttpServletRequest getRequest() {
        //从获取 RequestAttributes 中获取 HttpServletRequest 的信息
    	HttpServletRequest request = (HttpServletRequest) getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_REQUEST);
		return request;
	}
	
	/**
	 * 获取 HttpSession
	 */
	public static HttpSession getSession() {
        //从获取 RequestAttributes 中获取 HttpSession 的信息
    	HttpSession session = (HttpSession) getRequestAttributes().resolveReference(RequestAttributes.REFERENCE_SESSION);
		return session;
	}
	
	/**
	 * 获取 HttpServletResponse
	 */
	public static HttpServletResponse getResponse() {
		//获取 ServletRequestAttributes
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)getRequestAttributes();
        //从获取 ServletRequestAttributes 中获取 HttpServletResponse 的信息
    	HttpServletResponse response = servletRequestAttributes.getResponse();
		return response;
	}
	
	/**
	 * 获取 RequestAttributes
	 */
	private static RequestAttributes getRequestAttributes() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		assertRequestAttributes(requestAttributes);
		return requestAttributes;
        
    }
	
	/**
	 * 验证 RequestAttributes
	 */
	private static void assertRequestAttributes(RequestAttributes requestAttributes) {
		if (requestAttributes == null) {
            throw new RuntimeException("requestAttributes属性为null,请确认Web项目已经启动!");
        }
    }
}
